package com.mpp.cmn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mpp.cmn.mapper.DictMapper;
import com.mpp.cmn.service.DictService;
import com.mpp.common.util.StringUtils;
import com.mpp.model.entity.cmn.Dict;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author MMDZ
 * @date 2022/8/17 14:29
 * @description TODO
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    // 根据上级id获取子节点数据列表
    @Override
//    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long parentId) {
        List<Dict> dictList = baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", parentId));
        // 向list集合每个dict对象中设置hasChildren
        dictList.stream().forEach(dict -> {
            dict.setHasChildren(this.isChildren(dict.getId()));
        });
        return dictList;
    }

    @Override
    public void exportDictData(HttpServletResponse response) {

    }

    @Override
    public void importDictData(MultipartFile file) {

    }

    // 根据dictCode和value查询
    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode为空，直接根据value查询
        if (StringUtils.isEmpty(dictCode)) {
            //直接根据value查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        } else {
            //如果dictCode不为空，根据dictCode和value查询
            Dict codeDict = this.getDictByDictCode(dictCode);
            Long parent_id = codeDict.getId();
            //根据parent_id和value进行查询
            Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parent_id)
                    .eq("value", value));
            return finalDict.getName();
        }
    }

    // 根据dictCode获取下级节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        // 根据dictCode获取对应id
        Dict dict = this.getDictByDictCode(dictCode);
        // 根据id获取子节点
        List<Dict> chlidData = this.findChildData(dict.getId());
        return chlidData;
    }

    // 根据dictCode获取字典对象
    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

    // 判断id下面是否有子节点
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        return baseMapper.selectCount(wrapper) > 0;
    }
}
